package com.zjw.jdbc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * the dbcp utils
 * @author zjw
 *
 */
public class DBCPUtil {
	
	private static Properties dbcpProps;
	private static BasicDataSource dataSource;
	
	static{
		loadProperties();
		createDataSource();
	}
	
	private static void loadProperties() {
		dbcpProps = new Properties();
		String configName = "dbcp.properties";
		InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(configName);
		try {
			dbcpProps.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("load " + configName + " failed!!!!");
		} finally {
			if(null != inStream)
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
	}
	
	private static void createDataSource(){
		dataSource = new BasicDataSource();
		dataSource.setDriverClassName(getValue("dbcp.driver","com.mysql.jdbc.Driver"));
		dataSource.setUrl(getValue("dbcp.url","jdbc:mysql:///test"));
		dataSource.setUsername(getValue("dbcp.user","root"));
		dataSource.setPassword(getValue("dbcp.password","root"));
		
		dataSource.setInitialSize(getValue("dbcp.initialSize",10));
		dataSource.setMaxActive(getValue("dbcp.maxActive",20));
		dataSource.setMaxIdle(getValue("dbcp.maxIdle",10));
		dataSource.setMinIdle(getValue("dbcp.minIdle",8));
		dataSource.setMaxWait(getValue("dbcp.maxWait",1000 * 3));
		
		
	}
	
	private static String getValue(String key,String defaultValue){
		return dbcpProps.getProperty(key, defaultValue);
	}
	
	private static int getValue(String key, int defaultValue){
		int result = defaultValue;
		try {
			result = Integer.parseInt(dbcpProps.getProperty(key));
		} catch (NumberFormatException e) {
			System.out.println("key ["+key+"] must have a int value !!!!");
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static Connection getConnection() throws SQLException{
		return dataSource.getConnection();
	}
	
	public static BasicDataSource getDataSource(){
		return dataSource;
	}

}
